public class Leetcode162 {
    public static void main(String[] args) {
        System.out.println(findPeakElement(new int[]{1,2,1,3,5,6,4}));
    }

    public static int findPeakElement(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int middle = left + (right - left) / 2;

            if ((middle - 1 < 0 || nums[middle] > nums[middle - 1]) && (middle + 1 >= nums.length || nums[middle] > nums[middle + 1])) {
                return middle;
            }

            if (nums[middle] < nums[middle + 1]) {
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }

        return left;
    }
}
